package com.robot.tools.controller;

import com.robot.tools.service.OssService;
import entity.Result;
import entity.StatusCode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/oss")
public class OssController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OssService ossService;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(StatusCode.ERROR);
        }
        String fileName = file.getOriginalFilename();
        String filePath = "robot_member/upload/";
        String pathName = new File(filePath).getAbsolutePath() + "/" + fileName;
        File dest = new File(pathName);
        logger.info("dest="+dest.toString());
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            String res = ossService.upload(pathName);
            if ("".equals(res)) {
                return new Result(StatusCode.ERROR_FILE_FORMAT);
            }
            dest.delete();
            return new Result(StatusCode.SUCCESS_UPLOAD, res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("dest="+dest);
        return new Result(StatusCode.SUCCESS_UPLOAD, dest);
    }

}
